﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace ViewStateToDb
{
	internal static class AdoNetExtensions
	{
		public static void AddGuid(this SqlCommand cmd, string name, Guid value)
		{
			cmd.Parameters.Add("@" + name, System.Data.SqlDbType.UniqueIdentifier).Value = value;
		}
		public static void AddInt(this SqlCommand cmd, string name, int value)
		{
			cmd.Parameters.Add("@" + name, System.Data.SqlDbType.Int).Value = value;
		}
		public static void AddVarChar(this SqlCommand cmd, string name, string value)
		{
			cmd.Parameters.Add("@" + name, System.Data.SqlDbType.VarChar).Value = value;
		}
		public static void AddDateTime(this SqlCommand cmd, string name, DateTime value)
		{
			cmd.Parameters.Add("@" + name, System.Data.SqlDbType.DateTime).Value = value;
		}
		public static void AddVarBinary(this SqlCommand cmd, string name, byte[] value)
		{
			cmd.Parameters.Add("@" + name, System.Data.SqlDbType.VarBinary).Value = value;
		}

		public static string GetString(this IDataReader reader, string name)
		{
			return (string) reader[name];
		}
		public static DateTime GetDateTime(this IDataReader reader, string name)
		{
			return (DateTime) reader[name];
		}
		public static byte[] GetBytes(this IDataReader reader, string name)
		{
			return (byte[]) reader[name];
		}
		public static bool IsDBNull(this IDataReader reader, string name)
		{
			if (reader[name] == DBNull.Value)
				return true;

			return false;
		}
		public static void SetObjectName(this SqlCommand cmd, string name, string value)
		{
			cmd.CommandText = cmd.CommandText.Replace("$" + name, value);
		}
		public static T GetScalar<T>(this SqlCommand cmd)
		{
			object value = null;

			try
			{
				cmd.Connection.Open();
				value = cmd.ExecuteScalar();
				cmd.ExecuteNonQuery();
			}
			finally
			{
				cmd.Connection.Close();
			}

			if (value == null)
				return default(T);

			return (T) value;
		}
		public static void ExecuteNonQueryOpenCloseConnection(this SqlCommand cmd)
		{
			try
			{
				cmd.Connection.Open();
				cmd.ExecuteNonQuery();
			}
			finally
			{
				cmd.Connection.Close();
			}
		}
		public static void AddIntOutput(this SqlCommand cmd, string name)
		{
			cmd.Parameters.Add("@" + name, System.Data.SqlDbType.Int).Direction = System.Data.ParameterDirection.Output;
		}
	}
}
